package leetcode;

import java.util.*;

/**
 * @author Liangyaoyun
 */
public class leetCode107 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {

        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        //如果当前根节点不为空，则加入队列
        if (root != null) {
            queue.add(root);
        }
        while (!queue.isEmpty()) {

            List<Integer> list = new ArrayList<>();
            //将当前节点存放到数组里

            int n = queue.size();
            for (int i = 0; i < n; i++) {
                TreeNode treeNode = queue.poll();
                list.add(treeNode.val);
                if (treeNode.left != null) {
                    queue.offer(treeNode.left);
                }
                if (treeNode.right != null) {
                    queue.offer(treeNode.right);
                }
            }
            res.add(list);
        }
        Collections.reverse(res);
        return res;
    }
}
